package com.yeyks.mattress.function.aop;

import cn.hutool.core.util.StrUtil;
import com.yeyks.common.exception.ServiceException;
import com.yeyks.commonReference.append.app.TokenService;
import com.yeyks.commonReference.utils.UserUtils;
import com.yeyks.consumer.dal.domain.UserInfo;
import com.yeyks.consumer.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author fuchangshuai
 * @date 2019/05/15 17:56
 */
@Aspect
@Component
@Slf4j
public class TokenInterceptor {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private UserInfoService userInfoService;

    @Pointcut(value = "execution(* com.yeyks.mattress.controller.*..*(..))")
    public void webController() {
    }

    /**
     * 环绕切面
     * 第一个 * 代表任意修饰符及任意返回值
     * 第二个 * 定义在web包或者子包
     * 第三个 * 任意方法 ~ .. 匹配任意数量的参数
     */
    @Before("webController()")
    public void beforMehhod(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader("headerToken");
        if (StrUtil.isNotBlank(token)) {
            try {
                String userId = tokenService.getUserId(token);
                UserInfo userInfo = userInfoService.getById(Integer.valueOf(userId));
                UserUtils.putLoginUser(userInfo);
            } catch (Exception e) {
            }
        }
    }

}
